const router = require('koa-router')();
const xss = require('xss');
const Room = require('../entiity/Room');
const EventEmitter = require('node:events');
const {query} = require('../db');
const {message} = require('../utils')

// 储存所有房间实例
const rooms = new Map();

// 定义 '全局事件分发器' 
const eventEmitter = new EventEmitter();

// 监听房间发来的 '销毁房间' 消息
eventEmitter.on('destoryRoom', (roomId) => {
  rooms.delete(roomId);
})

router.all('/connect/:roomId/:userName',
  async (ctx, next) => {
    // 用户输入数据过滤
    ctx.params.roomId = xss(ctx.params.roomId);
    ctx.params.userName = xss(ctx.params.userName);

    // 路由守卫，防止进入不存在的房间
    if(await validRoomId(ctx.params)) { 
      next();
    } else {
      ctx.websocket.send(message('失败', 404, '此房间不存在'));
    }
  },
  async (ctx, next) => {
    const {roomId} = ctx.params;

    // 每进行一次websocket连接，判断该房间是否存在于 '全局房间实例表'，若不存在，新建 
    if(!rooms.has(roomId)) {
      rooms.set(roomId, new Room(roomId));
    }

    const room = rooms.get(roomId);

    // 给房间安装全局事件分发器
    room.eventEmitter = eventEmitter;

    // 让房间接待新来的用户
    room.receiveUser(ctx);

    next();
  }
)

async function validRoomId({roomId}) {
  try {
    const sql = `select * from room where roomId='${roomId}'`;
    const res = await query(sql);
    return res.length >= 1;
  }catch(e) {
    console.log(e);
  }
}

module.exports = router;
